<template>
  <div>
    <HomeView
      v-if="ifbut"
      :onSuccess="onSuccess"
    ></HomeView>
    <button @click="()=>ifbut = true">打开</button>
    <button @click="()=>ifbut = false">关闭</button>
    <button @click="onOrdinaryExport">导出</button>
  </div>
</template>

<script>
import HomeView from "./views/HomeView.vue";
export default {
  components: {
    HomeView,
  },
  data() {
    return {
      ifbut: false,
      Reflection: {
        姓名: "name",
        性别: "sex",
        手机号: "phoneNumber",
        角色: "roleName",
        工号: "workNumber",
        出生日期: "birthDay",
        学历: "degree",
        入职日期: "jobDateStart",
        离职日期: "jobDateEnd",
        部门: "organizationName",
      },
    };
  },
  methods: {
    derive(){
      const list = [
        {name:"张先丰",age:"男",time:"2023-10-15"},
        {name:"栗子",age:"女",time:"2023-6-15"}
      ]
      return this.onSortList(list)
    },
    onSortList(list){
      const sortOrder = [
      "name",
      "age",
      "time"
      ]
      // FilnalData 用来存放最后的数据
      const FilnalData = []
      list.forEach((item) => {
        const arr = []
        sortOrder.forEach((obj) => {
          if (obj === 'formOfEmployment') {
            arr.push(item[obj] === 1 ? '正式' : '非正式')
          } else {
            arr.push(item[obj])
          }
        })
        FilnalData.push(arr)
      })
      return FilnalData
    },

async onOrdinaryExport() {
      this.ExportLoading = true
      // derive() 这里是一个primise异步方法，所以要用await
      const FilnalData = await this.derive()
      //  import('@/vendor/Export2Excel') 懒加载  导入后，拿到excel对象 的对象中有export_json_to_excel 方法
      import('./views/AboutView').then((excel) => {
        excel.export_json_to_excel({
          header: [
        '姓名',
        '性别',
        '日期',
      ], //表头 必填
          data: FilnalData, //具体数据 必填
          filename: '员工信息表格',
          autoWidth: true,
          bookType: 'xlsx',
        })
      })
      this.ExportLoading = false
    },
    // 导入
    onSuccess(excelData) {
      const data = this.convertKeysToEnglish(this.Reflection,excelData.results);
      console.log(data);
    },
    convertKeysToEnglish(Reflection,val) {
      let arr = [];
      val.forEach((v) => {
        const result = {};
        for (let key in v) {
          if (Reflection[key]) {
            if (v[key] instanceof Date) {
              v[key] = v[key]
                .toLocaleDateString("zh-CN", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                })
                .replace(/\//g, "-");
            }
            result[Reflection[key]] = v[key];
          } else {
            result[key] = v[key];
          }
        }
        arr.push(result);
      });
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
</style>